List PatternsĀ¶
This demonstrates the mapping pattern.
Map is a mathematical term that means going from one value to a corresponding value.
This is also referred to as the transform pattern.
šØš¼āšØ smaller_numbers.py
Ā¶
Write a function that creates a new list where each item has been divided by 2.
You can pass lists to functions and return lists from functions.
This demonstrates the filter pattern.
A new collection is created with certain items filtered out.
This demonstrates the selection pattern.
A single item is selected from a collection.
This demonstrates the accumulator pattern.
total
accumulates the values in the collection.
Another way for list patternsĀ¶
InĀ [17]:
numbers = [1, 2, 3, 4, 5]
sum
Ā¶
InĀ [18]:
sum(numbers)
Out[18]:
15
InĀ [19]:
sum(numbers) / len(numbers)
Out[19]:
3.0
List comprehensionsĀ¶
Mapping patternĀ¶
InĀ [20]:
new_numbers = []
for number in numbers:
new_number = number + 7
new_numbers.append(new_number)
new_numbers
Out[20]:
[8, 9, 10, 11, 12]
InĀ [23]:
new_numbers = [number + 7 for number in numbers]
new_numbers
Out[23]:
[8, 9, 10, 11, 12]
InĀ [23]:
def add_seven(number):
return number + 7
new_numbers = [add_seven(number) for number in numbers]
new_numbers
Out[23]:
[8, 9, 10, 11, 12]
InĀ [24]:
[number / 3 for number in numbers]
Out[24]:
[0.3333333333333333, 0.6666666666666666, 1.0, 1.3333333333333333, 1.6666666666666667]
InĀ [25]:
[number ** 2 for number in numbers]
Out[25]:
[1, 4, 9, 16, 25]
InĀ [26]:
[number ** 0.5 for number in numbers]
Out[26]:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]
Filter patternĀ¶
InĀ [27]:
new_numbers = []
for number in numbers:
if number > 3:
new_numbers.append(number)
new_numbers
Out[27]:
[4, 5]
InĀ [28]:
[number for number in numbers if number > 3]
Out[28]:
[4, 5]
InĀ [29]:
[number for number in numbers if number % 2 == 0]
Out[29]:
[2, 4]
InĀ [30]:
[number for number in numbers if number * 5 < 20]
Out[30]:
[1, 2, 3]
All Together with comprehensionsĀ¶
InĀ [31]:
nums = [0, 7, 2, 14, 20, 32, 5, 12]
# subtract 7
nums = [number - 7 for number in nums]
# Keep 0 <= num <= 10
def is_keeper(number):
return 0 <= number <= 10
nums = [number for number in nums if is_keeper(number)]
print(nums)
[0, 7, 5]
Key IdeasĀ¶
- mapping pattern
- filter pattern
- selection pattern
- accumulator pattern
- List comprehensions
- mapping pattern
- filter pattern